package com.firstgroup.service.Interceptors;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.firstgroup.Utils.JwtUtil;
import com.firstgroup.domain.User;
import com.firstgroup.service.Impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 创作人 王箫凯
 * Date 2021/8/9
 * Time 16:39
 *
 * @author 王箫凯
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    @Resource
    UserServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        //获取token
        String token = request.getHeader("token");
        if (token==null) {
            log.info("不存在token，请进行登录");
            response.sendRedirect(request.getContextPath()+"/InterceptorResult/NotLogin");
            return false;
        }
        //验证token的问题
        if (!JwtUtil.verify(token)) {
            log.info("token 异常，可能为过期或者其他问题");
            response.sendRedirect(request.getContextPath()+"/InterceptorResult/BedToken");
            return false;
        }
        DecodedJWT decodedJWT = JwtUtil.jwtInf(token);
        String username=decodedJWT.getClaim("username").asString();
        User user=userService.findUser(username);
        if (user == null) {
            log.info("越级访问");
            response.sendRedirect(request.getContextPath()+"/InterceptorResult/NoPower");
            return false;
        }
        return true;
    }
}
